<template>
  <view class="location-monitor-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="header-title">位置监控</view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <!-- 筛选选项 -->
      <view class="tabs-container">
        <up-tabs 
          v-model="activeFilterTab" 
          :list="filterTabs" 
          @change="handleTabChange"
        ></up-tabs>
      </view>
      <view class="filter-actions">
        <view class="refresh-btn" @click="refreshInspectorLocations">
          <text class="refresh-icon" :class="{ 'refreshing': isRefreshing }">↻</text>
          <text>刷新</text>
        </view>
      </view>
    </view>

    <!-- 地图区域 -->
    <view class="map-container">
      <map 
        :latitude="mapCenter.latitude" 
        :longitude="mapCenter.longitude"
        :scale="14"
        :markers="markers"
        :show-location="true"
        :include-points="markers.length ? markers.map(m => ({latitude: m.latitude, longitude: m.longitude})) : []"
        class="map"
        @markertap="handleMarkerTap"
      ></map>
    </view>

    <!-- 巡检员列表 -->
    <view class="inspector-list">
      <view class="list-header">
        <text class="header-title">巡检员列表</text>
        <view class="refresh-btn" @click="refreshInspectorLocations">
          <image src="/static/icons/refresh-icon.svg" class="refresh-icon"></image>
          <text>刷新</text>
        </view>
      </view>
      
      <view class="list-content">
        <view 
          v-for="(inspector, index) in inspectorList" 
          :key="index" 
          class="list-item"
          @click="focusInspector(inspector)"
        >
          <view class="item-info">
            <view class="inspector-name">{{ inspector.name }}</view>
            <view class="inspector-id">ID: {{ inspector.employeeId }}</view>
          </view>
          <view class="item-status" :class="inspector.status">
            {{ getStatusText(inspector.status) }}
          </view>
        </view>
      </view>
    </view>

    <!-- 巡检员位置详情弹窗 -->
    <inspector-location-modal
      v-model:show="showLocationModal"
      :inspector-info="selectedInspector"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useLocation } from '@/hooks';
import { getGroupMembers } from '@/api/scheduling';
import { getInspectorLocations, getOnlineInspectorLocations } from '@/api/location';
import InspectorLocationModal from './components/InspectorLocationModal.vue';

// 筛选选项卡数据
const filterTabs = [
  { name: '全部巡检员' },
  { name: '在岗巡检员' },
];
const activeFilterTab = ref(0);

// 地图中心点
const mapCenter = ref({
  latitude: 39.9042,
  longitude: 116.4074
});

// 巡检员列表数据
const inspectorList = ref([]);

// 地图标记点
const markers = ref([]);

// 获取位置相关功能
const { getLocation } = useLocation();

// 刷新状态
const isRefreshing = ref(false);

// 处理选项卡切换
const handleTabChange = (e) => {
  // up-tabs组件传递的是事件对象，包含index属性
  console.log('选项卡切换事件：', e);
  activeFilterTab.value = e.index;
  loadInspectorList();
};

// 获取巡检员状态文本
const getStatusText = (status) => {
  const statusMap = {
    'online': '在线',
    'offline': '离线',
    'working': '工作中'
  };
  return statusMap[status] || '未知';
};

// 加载巡检员列表
const loadInspectorList = async () => {
  try {
    isRefreshing.value = true;
    
    // 根据筛选选项调用不同的API
    const params = {};
    let result;
    
    if (activeFilterTab.value === 1) {
      // 获取在岗巡检员
      result = await getOnlineInspectorLocations(params);
    } else {
      // 获取全部巡检员
      result = await getInspectorLocations(params);
    }
    
    // API调用成功后处理数据
    // inspectorList.value = result.data;
    
    // 由于API可能尚未实现，使用模拟数据
    const mockData = generateMockData();
    console.log('当前选中的选项卡值：', activeFilterTab.value);
    inspectorList.value = activeFilterTab.value === 1 
      ? mockData.filter(item => item.status !== 'offline')
      : mockData;
    
    // 更新地图标记点
    updateMapMarkers();
    
    // 显示刷新成功提示
    uni.showToast({
      title: '数据已更新',
      icon: 'success',
      duration: 1500
    });
  } catch (error) {
    console.error('加载巡检员列表失败', error);
    uni.showToast({
      title: '加载巡检员列表失败',
      icon: 'none'
    });
  } finally {
    isRefreshing.value = false;
  }
};

// 更新地图标记点
const updateMapMarkers = () => {
  markers.value = inspectorList.value.map((inspector, index) => {
    return {
      id: inspector.id,
      latitude: inspector.latitude,
      longitude: inspector.longitude,
      width: 30,
      height: 30,
      title: inspector.name,
      iconPath: getMarkerIcon(inspector.status),
      callout: {
        content: `${inspector.name}(${getStatusText(inspector.status)})`,
        color: '#333',
        fontSize: 12,
        borderRadius: 4,
        bgColor: '#fff',
        padding: 8,
        display: 'BYCLICK'
      }
    };
  });
};

// 获取标记点图标
const getMarkerIcon = (status) => {
  const iconMap = {
    'online': '/static/images/marker_online.svg',
    'offline': '/static/images/marker_offline.svg',
    'working': '/static/images/marker_working.svg'
  };
  return iconMap[status] || '/static/images/marker_default.svg';
};

// 刷新巡检员位置
const refreshInspectorLocations = () => {
  if (isRefreshing.value) return;
  loadInspectorList();
};

// 位置详情弹窗
const showLocationModal = ref(false);
const selectedInspector = ref(null);

// 聚焦到特定巡检员
const focusInspector = (inspector) => {
  // 更新地图中心点
  mapCenter.value = {
    latitude: inspector.latitude,
    longitude: inspector.longitude
  };
  
  // 显示巡检员详情
  selectedInspector.value = inspector;
  showLocationModal.value = true;
};

// 处理地图标记点点击
const handleMarkerTap = (e) => {
  const markerId = e.detail.markerId;
  const inspector = inspectorList.value.find(item => item.id === markerId);
  if (inspector) {
    selectedInspector.value = inspector;
    showLocationModal.value = true;
  }
};

// 生成模拟数据
const generateMockData = () => {
  return [
    {
      id: 1,
      name: '张三',
      employeeId: 'EMP001',
      status: 'online',
      latitude: 39.9042,
      longitude: 116.4074
    },
    {
      id: 2,
      name: '李四',
      employeeId: 'EMP002',
      status: 'working',
      latitude: 39.9142,
      longitude: 116.4174
    },
    {
      id: 3,
      name: '王五',
      employeeId: 'EMP003',
      status: 'offline',
      latitude: 39.8942,
      longitude: 116.3974
    },
    {
      id: 4,
      name: '赵六',
      employeeId: 'EMP004',
      status: 'online',
      latitude: 39.9242,
      longitude: 116.4274
    },
    {
      id: 5,
      name: '钱七',
      employeeId: 'EMP005',
      status: 'working',
      latitude: 39.8842,
      longitude: 116.3874
    }
  ];
};

// 获取当前位置
const getCurrentLocation = async () => {
  try {
    const locationData = await getLocation({
      type: 'gcj02',
      isHighAccuracy: true
    });
    
    // 更新地图中心点
    mapCenter.value = {
      latitude: locationData.latitude,
      longitude: locationData.longitude
    };
  } catch (error) {
    console.error('获取当前位置失败', error);
    // 使用默认位置
  }
};

// 页面加载时执行
onMounted(() => {
  // 获取当前位置
  getCurrentLocation();
  
  // 加载巡检员列表
  loadInspectorList();
});
</script>

<style scoped lang="scss">
.location-monitor-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  padding: 30rpx 0;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.filter-section {
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .tabs-container {
    flex: 1;
    background-color: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    margin-right: 20rpx;
  }
  
  .filter-actions {
    display: flex;
    align-items: center;
    
    .refresh-btn {
      display: flex;
      align-items: center;
      padding: 10rpx 20rpx;
      font-size: 24rpx;
      color: #2c5aa0;
      background-color: #f0f7ff;
      border-radius: 30rpx;
      
      .refresh-icon {
        font-size: 28rpx;
        margin-right: 8rpx;
        transition: transform 0.5s ease;
        display: inline-block;
        
        &.refreshing {
          animation: rotating 1s linear infinite;
        }
      }
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.map-container {
  height: 500rpx;
  border-radius: 12rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
  border: 1px solid #e8e8e8;
  
  .map {
    width: 100%;
    height: 100%;
  }
}

.inspector-list {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1px solid #eee;
    
    .header-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }
    
    .refresh-btn {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #2c5aa0;
      
      .refresh-icon {
        width: 28rpx;
        height: 28rpx;
        margin-right: 8rpx;
      }
    }
  }
  
  .list-content {
    padding-top: 20rpx;
    
    .list-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-info {
        .inspector-name {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .inspector-id {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .item-status {
        padding: 6rpx 16rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        
        &.online {
          background-color: #e6f7ff;
          color: #1890ff;
        }
        
        &.offline {
          background-color: #f5f5f5;
          color: #999;
        }
        
        &.working {
          background-color: #f6ffed;
          color: #52c41a;
        }
      }
    }
  }
}
</style>